<template>
  <div class="reset-password-container">
    <el-card class="reset-password-card">
      <h2 class="reset-password-title">重置密码</h2>
      
      <el-form
        @submit.prevent="submitForm"
        :model="passwordForm"
        :rules="rules"
        ref="formRef"
        label-width="90px"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="passwordForm.email" type="email" autocomplete="email" />
        </el-form-item>
        
        <el-form-item label="验证码" prop="code">
          <el-input v-model="passwordForm.code" required>
            <template #append>
              <el-button
                @click="sendVerificationCode"
                :disabled="isSending || isLoading"
              >
                {{ codeButtonText }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
        
        <el-button
          type="primary"
          native-type="submit"
          class="submit-button"
          :loading="isLoading"
        >
          {{ isLoading ? '提交中...' : '提交' }}
        </el-button>
        
        <div v-if="error" class="error-message">
          {{ error }}
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { auth } from '@/utils/api.js';

export default {
  data() {
    return {
      passwordForm: {
        email: '2654207269@qq.com',
        code: '',
        newPassword: 'newPassword1234',
        confirmPassword: 'newPassword1234'
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^\d{4,6}$/, message: '请输入4-6位数字验证码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, message: '密码长度至少8位', trigger: 'blur' },
          {
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,}$/,
            message: '密码必须包含大小写字母和数字',
            trigger: 'blur'
          }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.passwordForm.newPassword) {
                callback(new Error('两次输入密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },
      isSending: false,
      isLoading: false,
      codeButtonText: '获取验证码',
      countdown: 60,
      error: null,
      timer: null, // 新增
      storedEmail: null,
      storedTimestamp: null
    };
  },
  mounted() {
    this.restoreCountdown();
  },
  beforeUnmount() {
    if (this.timer) clearInterval(this.timer);
  },
  watch: {
    'passwordForm.email'(newEmail) {
      if (newEmail !== this.storedEmail) {
        this.resetCountdown();
        localStorage.removeItem('resetVerificationCodeState');
      } else {
        this.restoreCountdown();
      }
    }
  },
  methods: {
    resetCountdown() {
      this.isSending = false;
      this.codeButtonText = '获取验证码';
      this.countdown = 60;
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    async sendVerificationCode() {
      if (!this.passwordForm.email) {
        this.$message.error('请先填写邮箱地址');
        return;
      }
      this.isSending = true;
      this.countdown = 60;
      if (this.timer) clearInterval(this.timer);
      this.codeButtonText = `${this.countdown}秒后重试`;
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
          this.codeButtonText = `${this.countdown}秒后重试`;
        } else {
          clearInterval(this.timer);
          this.timer = null;
          this.isSending = false;
          this.codeButtonText = '获取验证码';
          localStorage.removeItem('resetVerificationCodeState');
        }
      }, 1000);
      try {
        await auth.sendResetCode(this.passwordForm.email);
        this.$message.success('验证码已发送至您的邮箱，请查收');
        localStorage.setItem('resetVerificationCodeState', JSON.stringify({
          email: this.passwordForm.email,
          timestamp: Date.now()
        }));
      } catch (error) {
        this.$message.error(error.message || '获取验证码失败');
        clearInterval(this.timer);
        this.timer = null;
        this.isSending = false;
        this.codeButtonText = '获取验证码';
      }
    },
    restoreCountdown() {
      const storedData = localStorage.getItem('resetVerificationCodeState');
      if (!storedData) return;
      try {
        const { email, timestamp } = JSON.parse(storedData);
        const now = Date.now();
        const timeDiff = (now - timestamp) / 1000;
        if (email === this.passwordForm.email && timeDiff < 60) {
          this.storedEmail = email;
          this.storedTimestamp = timestamp;
          this.isSending = true;
          this.countdown = Math.max(60 - Math.floor(timeDiff), 1);
          this.codeButtonText = `${this.countdown}秒后重试`;
          if (this.timer) clearInterval(this.timer);
          this.timer = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--;
              this.codeButtonText = `${this.countdown}秒后重试`;
            } else {
              clearInterval(this.timer);
              this.timer = null;
              this.isSending = false;
              this.codeButtonText = '获取验证码';
              localStorage.removeItem('resetVerificationCodeState');
            }
          }, 1000);
        }
      } catch (error) {
        localStorage.removeItem('resetVerificationCodeState');
      }
    },
    async submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          this.isLoading = true;
          try {
            // 组装后端需要的参数
            const payload = {
              email: this.passwordForm.email,
              verificationCode: this.passwordForm.code,
              newpassword: this.passwordForm.newPassword
            };
            await auth.resetPassword(payload);
            this.$message.success('密码重置成功');
            // 清空表单
            this.passwordForm.email = '';
            this.passwordForm.code = '';
            this.passwordForm.newPassword = '';
            this.passwordForm.confirmPassword = '';
            this.resetCountdown();
            this.$router.push('/login');
          } catch (error) {
            this.error = error.message || '重置密码失败';
          } finally {
            this.isLoading = false;
          }
        } else {
          this.error = '请修正表单中的错误';
        }
      });
    }
  }
};
</script>

<style scoped>
.reset-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.reset-password-card {
  width: 400px;
  padding: 20px;
}

.reset-password-title {
  text-align: center;
  margin-bottom: 20px;
}

.submit-button {
  width: 100%;
}

.error-message {
  color: red;
  margin-top: 10px;
  text-align: center;
}
</style>
